<!--
  - Copyright (c) 2021.  北京维数科技有限公司
  - Date :  2021/3/25
  - Author ：F12 Console=> atob("MzMxNDkxODAwQHFxLmNvbQ==")
  - Version ：1.0.0
  -->

<template>
    <div class="login-container login-turing-container">
        <!--登录模块-->
        <div class="index-login-section">
          <!-- 登录 -->
          <el-form class="login-form" autoComplete="on" :model="loginForm" :rules="loginRules" ref="loginForm" label-position="left" v-if="login" :key="1" @keydown.enter.native="handleLogin">
            <div class="img-logo"><img :src="imglogo" alt="logo"></div>
            <el-form-item prop="username" class="username">
              <el-input name="username" type="text" v-model.trim="loginForm.username" autoComplete="on" placeholder="用户名">
                <i slot="prefix" class="el-input__icon"><icon-svg icon-class="username" style="fill:rgba(34, 55, 74, 0.5)" /></i>
              </el-input>
            </el-form-item>

            <el-form-item prop="password">
              <el-input name="password" :type="passwordType" v-model.trim="loginForm.password" placeholder="密码">
                <i slot="prefix" class="el-input__icon"><icon-svg icon-class="passwd" style="fill:rgba(34, 55, 74, 0.5)" /></i>
              </el-input>
            </el-form-item>
            <el-form-item prop="code" class="code-box">
              <el-input name="code" type="text" class="validate-img" v-model.trim="loginForm.code" placeholder="验证码">
                <template slot="append">
                  <div class="code" @click="changeImgcode"><img :src="validateimg" alt="验证码"></div>
                </template>
              </el-input>

            </el-form-item>
            <el-button type="primary" class="login-bottom-submit" :loading="loading" @click="handleLogin" id="submitbtn">登录</el-button>
            <div class="footer">
              <div class="footer-box">
                <span>
                  <el-checkbox class="checkbox" v-model="checked">记住我</el-checkbox>
                </span>
                <span class="forget" @click="forgetPassword">忘记密码 ？</span>
              </div>
            </div>
          <!-- 特殊图形 -->

          </el-form>

          <!-- 忘记密码 -->
          <el-form class="login-form" :model="forgetForm" :rules="forgetRules" ref="forgetForm" label-position="left" v-else :key="2" @submit.native.prevent>
            <h3>忘记密码</h3>
            <el-form-item class="username" prop="fusername">
              <el-input type="text" v-model.trim="forgetForm.fusername" placeholder="用户名"></el-input>
            </el-form-item>
            <el-form-item class="code-box code-num" prop="phonecode">
              <el-input type="text" v-model.trim="forgetForm.phonecode" maxlength="10" placeholder="验证码"></el-input>
              <el-button class="code-btn" type="text" @click="sendPhonecode" :disabled="isOvertime">{{phoneword}}</el-button>
            </el-form-item>
            <el-form-item prop="newpassword">
              <el-input name="newpassword" type="password" v-model.trim="forgetForm.newpassword" placeholder="新密码"></el-input>
            </el-form-item>
            <el-form-item prop="confirmpassword">
              <el-input name="confirmpassword" type="password" v-model.trim="forgetForm.confirmpassword" placeholder="确认新密码"></el-input>
            </el-form-item>
            <el-button type="primary" class="login-bottom-submit" @click.native.prevent="handleForget" native-type="submit">确定</el-button>
            <div class="backlogin">
              <el-button type="text" @click="backlogin">
                <i class="el-icon-back"></i>返回登录</el-button>
            </div>
          </el-form>
        </div>
      <!-- 底部信息 -->
      <div class="index-footer">
        <div class="index-footer-wrap">
           <div class="index-footer-wrapbottom">
               <!--<el-popover-->
                       <!--placement="right"-->
                       <!--width="100"-->
                       <!--popper-class="code-popper"-->
                       <!--trigger="hover">-->
                   <!--<div class="codeimg-group">-->
                       <!--<div class="codeimg-item">-->
                           <!--<img src="@/assets/default-images/axg.jpg">-->
                           <!--<p>安卓版下载</p>-->
                       <!--</div>-->
                   <!--</div>-->
                   <!--<i class="class-icon-show" slot="reference">-->
                       <!--<icon-svg icon-class="qbcode" />-->
                   <!--</i>-->
               <!--</el-popover>-->
               <br>
                Copyright &copy;  武汉中科图灵科技有限公司, All Rights Reserved.
               <!--&copy;2019 Terminus Technologies Co., Ltd . All Rights Reserved.-->
               <!--<br>渝ICP备14002581号-->
           </div>
        </div>
      </div>
  </div>
</template>
<script>
  import { randomn } from "@/utils";
  import imglogo from '@/assets/login-bg_images/login-r.png'
  import Cookies from 'js-cookie'
import { isvalidPhone } from "@/utils/validate";
var validPhone = (rule, value, callback) => {
  if (!value) {
    callback(new Error("请输入手机号码"));
  } else if (!isvalidPhone(value)) {
    callback(new Error("请输入正确的手机号码"));
  } else {
    callback();
  }
};
export default {
  name: "login",
  data() {
    const validatePass = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("密码不能小于6位"));
      } else {
        callback();
      }
    };
    const confirmPw = (rule, value, callback) => {
      if (value !== this.forgetForm.newpassword) {
        callback(new Error("密码不一致"));
      } else {
        callback();
      }
    };
    return {
      checked:false,
      imglogo,
      phoneword: "获取验证码",
      isOvertime: false,
      labelPosition: "top",
      validateimg: "/api/admin/image/getCode",
      login: true,
      sizeForm: {
        type: ""
      },
      forgetForm: {
        fusername: "",
        phonecode: "",
        newpassword: "",
        confirmpassword: ""
      },
      forgetRules: {
        fusername: [
          {
            required: true,
            message: "用户名不能为空",
            trigger: "blur"
          },
          {
            min: 3,
            max: 20,
            message: "长度在 3 到 20 个字符",
            trigger: "blur"
          }
        ],
        phonecode: [
          {
            required: true,
            message: "验证码不能为空",
            trigger: "blur"
          }
        ],
        newpassword: [
          {
            required: true,
            message: "新密码不能为空",
            trigger: "blur"
          },
          {
            min: 6,
            max: 18,
            message: "长度在 6 到 18 个字符",
            trigger: "blur"
          }
        ],
        confirmpassword: [
          {
            required: true,
            message: "密码不一致",
            trigger: "blur"
          },
          {
            required: true,
            trigger: "blur",
            validator: confirmPw
          }
        ]
      },
      loginForm: {
        username: localStorage.getItem("logined") || "",
        password: "",
        code: "",
        image:""
      },
      loginRules: {
        username: [
          {
            required: true,
            message: "用户名不能为空",
            trigger: "blur"
          },
          {
            min: 3,
            max: 20,
            message: "长度在 3 到 20 个字符",
            trigger: "blur"
          }
        ],
        password: [
          {
            required: true,
            trigger: "blur",
            validator: validatePass
          }
        ],
        code: [
          {
            required: true,
            message: "验证码不能为空",
            trigger: "blur"
          },
          {
            min: 4,
            max: 4,
            message: "验证码不正确",
            trigger: "blur"
          }
        ]
      },
      passwordType: "password",
      loading: false,
      showDialog: false
    };
  },
  mounted() {
      if(localStorage.getItem("logined")!==null){
          this.checked = true
      }
  },
  methods: {
    getRandom() {
      return Math.random()
        .toString(36)
        .substr(2);
    },
    changeImgcode() {
      if (this.validateimg.indexOf("?") > 0) {
        this.validateimg =
          this.validateimg.split("?")[0] + "?" + this.getRandom();
      } else {
        this.validateimg = this.validateimg + "?" + this.getRandom();
      }
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
    },
    handleLogin() { 
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          let self = this;
          this.loginForm.image = Cookies.get('image')
          self.$store
          .dispatch("LoginByUsername", self.loginForm)
          .then(() => {
            self.$cookie.set('username', self.loginForm.username);
            self.$router.push({
              path: "/"
            });
            // 如果勾选了记住
            if (self.checked) {
              localStorage.setItem("logined", self.loginForm.username);
            }else{
              if(self.loginForm.username===localStorage.getItem("logined")){
                localStorage.removeItem("logined")
              }
            }
          })
          .catch(() => {
            self.loading = false;
            self.changeImgcode();
          });

        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    apiSendcode() {
      let self = this;
      this.loading = true;
      this.$axios
        .get("/api/admin/valicode/sms", {
          params: { username: self.forgetForm.fusername }
        })
        .then(function(response) {
          self.loading = false;
          let res = response.data;
          if (res.status === 200) {
            self.$notify({
              title: "成功",
              message: "验证码已发送到"+res.data,
              type: "success",
              position: "bottom-right"
            });

            self.showcodetime();
          } else {
            self.$notify({
              title: "警告",
              message: "用户名不存在！",
              type: "warning",
              position: "bottom-right"
            });
          }
        })
        .catch(function(error) {
          self.loading = false;
          self.$message({
            message:error.response.data.message,
            type: 'warning'
          });
        });
    },
    showcodetime() {
      if (this.isOvertime) {
        return false;
      }
      let that = this,
        time = 60;
      var sendTimer = setInterval(function() {
        that.isOvertime = true;
        time--;
        that.phoneword = "已发送(" + time + "s)";
        if (time < 0) {
          that.isOvertime = false;
          clearInterval(sendTimer);
          that.phoneword = "获取验证码";
        }
      }, 1000);
    },
    sendPhonecode() {
      this.apiSendcode();
    },
    handleForget() {
      this.$refs.forgetForm.validate(valid => {
        if (valid) {
          let self = this;

          this.$axios
            .post("/api/admin/user/updatepwd", this.$qs.stringify({
              username: self.forgetForm.fusername,
              code: self.forgetForm.phonecode,
              pwd: window.btoa(window.btoa(self.forgetForm.confirmpassword) + randomn(7))
            }))
            .then(function(response) {
              let res = response.data;
              if (res.status===200) {
                self.$message({
                  showClose: true,
                  message: '修改密码成功',
                  type: 'success'
                });
                setTimeout(() => {
                  location.reload();
                }, 300);
              }else{
                self.$message({
                  showClose: true,
                  message: res.message,
                  type: 'warning'
                });
              }
            }).catch(function(error) {
            self.loading = false;
            self.$message({
              message:error.response.data.message,
              type: 'warning'
            });
          });
        } else {
          return false;
        }
      });
    },
    afterQRScan() {
      // const hash = window.location.hash.slice(1)
      // const hashObj = getQueryObject(hash)
      // const originUrl = window.location.origin
      // history.replaceState({}, '', originUrl)
      // const codeMap = {
      //   wechat: 'code',
      //   tencent: 'code'
      // }
      // const codeName = hashObj[codeMap[this.auth_type]]
      // if (!codeName) {
      //   alert('第三方登录失败')
      // } else {
      //   this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
      //     this.$router.push({ path: '/' })
      //   })
      // }
    },
    forgetPassword() {
      //this.$refs["loginForm"].resetFields();
      //this.forgetForm.phonecode = "";
      //this.$refs["forgetForm"].resetFields();
      this.login = false;
      this.forgetForm.fusername = JSON.parse(JSON.stringify(this.loginForm.username))
    },
    backlogin() {
      this.$refs["forgetForm"].resetFields();
      this.login = true;
    },
    submit() {}
  },
  created() {
    // window.addEventListener('hashchange', this.afterQRScan)
    //this.getValidateImg()
  },
  destroyed() {
    // window.removeEventListener('hashchange', this.afterQRScan)
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
$bg: #2d3a4b;
$light_gray: #000;

/* reset element-ui css */
.login-container {
  background-image: url(../../../src/assets/login-bg_images/login-bg.png);
  background-size: cover;
  background-position: 50%;
  .el-form-item {
    height: 39px;
    width: 343px;
    margin: 20px auto;
  }
  .el-form-item.is-required .el-form-item__label:before {
    content: "";
  }
  .el-input--medium .el-input__inner {
    border: 2px solid #e0e0e0;
  }
  .el-input__inner{
    background: #fff;
    color:#000;
  }
  .el-input__prefix{
    left: 10px;
  }
  .el-input {
    input {
      &:-webkit-autofill {
        -webkit-box-shadow: 0 0 0px 1000px #fff inset !important;
        -webkit-text-fill-color: #000 !important;
      }
    }
  }
  .validate-img {
    .el-input-group__append {
      padding: 0 85px;
      background: #fff;
      border: 0;
    }
  }
  .code-btn.is-disabled{
      span{
        color: #c0c4cc;
      }
  }
}
</style>

<style rel="stylesheet/scss" lang="scss" scoped>
@import "src/styles/mixin.scss";
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;
.login-container {
  min-height:100vh;
  @include relative;
  display: flex;
  align-items: center;
  .index-login-section{
    max-width: 1200px;
    width: 960px;
    height: 480px;
    margin: 0 auto;
    background: url(../../../src/assets/login-bg_images/login-left.png) no-repeat center right;
    .img-logo{
      padding-top: 30px;
      padding-bottom: 30px;
      padding-right: 30px;
      text-align: center;
      img{
        display: inline-block;
      }
    }
    .login-bottom-submit{
      width:343px;
      height:39px;
      display: flex;
      justify-content: center;
      margin: 30px auto 20px auto;
      background:linear-gradient(90deg,rgba(80,227,194,1) 0%,rgba(2,92,94,1) 100%);
      box-shadow:0px 2px 8px 0px rgba(80,227,194,0.5);
    }
  }
  .login-form {
    width: 480px;
    height:100%;
    padding: 1px 35px 15px;
    background-color: #fff;
    position: relative;
    &:after{
      content:'';
      position: absolute;
      top:0;
      width: 100px;
      bottom: 0;
      right: -100px;
      background: #fff;
      clip-path: polygon(0 0,100% 50%,0 100%,0 100%);
    }
    h3 {
      font-size: 31px;
      text-align: left;
      margin-left: 10px;
    }
    .username {
      margin-top: 30px;
    }
    .el-checkbox__input {
      border: 1px solid #37B8A2;
    }
    .checkbox {
      color: #37B8A2;
    }
    .footer{
      width: 348px;
      margin: 0 auto;
    }
    .forget {
      display: inline-block;
      padding-left: 10px;
      line-height: 19px;
      font-size: 14px;
      color: #37B8A2;
      cursor: pointer;
    }
    .footer-box {
      display: flex;
      justify-content: space-between;
    }
  }
  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;
    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }
  .title-container {
    position: relative;
    .title {
      font-size: 26px;
      font-weight: 400;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
  .thirdparty-button {
    position: absolute;
    right: 35px;
    bottom: 28px;
  }
  .code-box {
    position: relative;
    .code {
      position: absolute;
      top: 0;
      right: 0;
      background-color: #eee;
      width: 170px;
      height: 36px;
      img {
        border: 0;
      }
    }
  }
  .code-num {
    position: relative;
    .code-btn {
      width: 121px;
      height: 36px;
      border: 2px solid #e0e0e0;
      position: absolute;
      top:0;
      right: 0;
    }
  }
  .backlogin {
    text-align: center;
    margin-top: 10px;
  }
}
.index-footer{
  position: absolute;
  bottom: 60px;
  width: 100%;
  .index-footer-wrap{
    max-width: 1200px;
    margin: 0 auto;
    .index-footer-wrapbottom{
      text-align: center;
      color: rgba(216, 216, 216, 0.5);
      font-size: 16px;
      line-height: 22px;
        .class-icon-show{
            font-size: 30px;
            cursor: pointer;
        }
    }
  }
}

</style>
